package sg.edu.nus.iss.team2s.jass.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import sg.edu.nus.iss.team2s.jass.dto.Company;
/**
 * IO data access implementation for Company
 * @author Zhang JinZhong
 * @version 1.0
 */
public class CompanyDataAccessImpl implements DataAccessI {

	@Override
	public List<Object> parseObjectsFromReader(BufferedReader in) throws IOException {
		List<Object> objList = new ArrayList<Object>();
		String lineStr;
		int lineCount = 0;
		Company objCompany = null;
		String[] str = new String[9];
		while((lineStr = in.readLine()) != null){
			str[lineCount] = lineStr.substring(lineStr.indexOf("=")+1,lineStr.length());
			lineCount++;
			if(lineCount == str.length){
				objCompany = new Company(str[0],str[1],str[2],str[3],str[4],str[5],str[6],str[7],str[8]);
				objList.add(objCompany);
				lineCount = 0;
			}
		}
		return objList;
	}

	@Override
	public void writeObjectsToWriter(List<Object> objects,
			BufferedWriter out) throws IOException {
		int lineCount = 0;
		Iterator<Object> iterator = objects.iterator();
		while(iterator.hasNext()){
			Company objCompany = (Company)iterator.next();
			if(objCompany.getCompanyId() != null){
				out.write(recordStr("companyId",lineCount,objCompany.getCompanyId()));
			}
			else{
				out.write(recordStr("companyId",lineCount,String.valueOf(lineCount)));
			}
			out.newLine();
			out.write(recordStr("advertiserId",lineCount,objCompany.getAdvertiserId()));
			out.newLine();
			out.write(recordStr("showName",lineCount,objCompany.getShowName()));
			out.newLine();
			out.write(recordStr("name",lineCount,objCompany.getName()));
			out.newLine();
			out.write(recordStr("description",lineCount,objCompany.getDescription()));
			out.newLine();
			out.write(recordStr("address",lineCount,objCompany.getAddress()));
			out.newLine();
			out.write(recordStr("hrContact",lineCount,objCompany.getHrContact()));
			out.newLine();
			out.write(recordStr("telephone",lineCount,objCompany.getTelephone()));
			out.newLine();
			out.write(recordStr("email",lineCount,objCompany.getEmail()));
			out.newLine();
			lineCount++;
		}
	}

	private String recordStr(String fieldName,int count,String fieldValue)
	{
		if(fieldValue != null){
			return fieldName+count+"="+fieldValue;
		}
		else{
			return fieldName+count+"=";
		}
	}
}
